﻿using System;
using System.Collections.Generic;
using WordXmlNode = Microsoft.Office.Core.CustomXMLNode;
using System.Windows.Media.Imaging;
using System.Windows;

namespace CodeCounsel.Office.DatabindingToolkit
{
    public class CustomXmlNode
        : DependencyObject
    {
        public static readonly DependencyProperty ProposedTypeProperty =
            DependencyProperty.Register("ProposedType", typeof(ControlType), typeof(CustomXmlNode), new UIPropertyMetadata(null));
    
        WordXmlNode _wordXmlNode = null;
        List<CustomXmlNode> _xmlNodes = null;
        CustomXmlPart _owner = null;

        public ControlType ProposedType
        {
            get { return (ControlType)GetValue(ProposedTypeProperty); }
            set { SetValue(ProposedTypeProperty, value); }
        }

        public IEnumerable<ControlType> AllowedTypes
        {
            get { return ControlTypes.All; }
        }
        
        public CustomXmlPart Owner
        {
            get { return _owner; }
        }

        public string Name
        {
            get { return _wordXmlNode.BaseName; }
        }

        public bool HasChildNodes
        {
            get { return _xmlNodes.Count > 0; }
        }

        public string XPath
        {
            get { return _wordXmlNode.XPath; }
        }

        public string NamespaceUri
        {
            get { return _wordXmlNode.NamespaceURI; }
        }

        public IEnumerable<CustomXmlNode> ChildNodes
        {
            get { return _xmlNodes; }
        }

        public CustomXmlNode(CustomXmlPart owner, WordXmlNode wordXmlNode)
        {
            _owner = owner;
            ProposedType = wordXmlNode.ChildNodes.Count > 0 ? null : ControlTypes.Text;
            _wordXmlNode = wordXmlNode;
            _xmlNodes = new List<CustomXmlNode>();
            if (wordXmlNode.ChildNodes != null)
            {
                foreach (WordXmlNode childWordXmlNode in wordXmlNode.ChildNodes)
                {
                    if (childWordXmlNode.NodeType == Microsoft.Office.Core.MsoCustomXMLNodeType.msoCustomXMLNodeElement)
                    {
                        AddXmlNode(childWordXmlNode);
                    }
                }
            }
        }

        void AddXmlNode(WordXmlNode wordXmlNode)
        {
            _xmlNodes.Add(new CustomXmlNode(_owner, wordXmlNode));
        }
    }
}
